﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//Adding
using System.Data;
using KPIS.GERP.ESS.DAL;
using KPIS.GERP.ESS.APP.App_UI.Commons;
using KPIS.GERP.ESS.BLL;
using Novacode;
using System.Drawing;

namespace KPIS.GERP.ESS.APP.App_UI.Forms
{
    public partial class frmGetDocxReport : System.Web.UI.Page
    {
        #region Fields

        private string _docName;
        private string _refNo;
        private string _refReturn;
        private string _clNo;

        D_FimMoneyRequest req = new D_FimMoneyRequest();
        Main main = new Main();
        MailMerge mailMerge = new MailMerge();
        ESS.BLL.B_MessageSend send = new ESS.BLL.B_MessageSend();
        B_HrmEmployees emplist = new B_HrmEmployees();

        FIM_MoneyReturnDtls.FIM_MoneyReturnDtls red = new FIM_MoneyReturnDtls.FIM_MoneyReturnDtls();
        DAL.D_FimMoneyReturn re2 = new DAL.D_FimMoneyReturn();
       
        //string allower1 = "อนุวัฒน์ ศุภชุติกุล";
        //string allower2 = "ผู้อำนวยการ";
        //string allowerPosition1 = "กิตตินันท์ อนรรฆมณี";
        //string allowerPosition2 = "รองผู้อำนวยการ";
        //string allowerDesc2 = "ปฏิบัติงานแทนผู้อำนวยการ";

        #endregion

        #region Properties

        public string DocName
        {
            get { return _docName; }
            set { _docName = value; }
        }

        public string RefNo
        {
            get { return _refNo; }
            set { _refNo = value; }
        }

        public string RefReturn
        {
            get { return _refReturn; }
            set { _refReturn = value; }
        }

        public string CLNo
        {
            get { return _clNo; }
            set { _clNo = value; }
        }
        #endregion

        #region Events

        protected void Page_Load(object sender, EventArgs e)
        {
            this.DocName = Request.QueryString["arg1"];
            this.RefNo = Request.QueryString["arg2"];

            if (Request.QueryString["arg3"].Trim() != "")
            {
                this.RefReturn = Request.QueryString["arg3"];
            }
            else
            {
                this.RefReturn = null;
            }

            this.CLNo = Request.QueryString["arg4"];

            if (this.DocName == "B")
            {
                ReportMoneyReqContracts();
            }
            else if (this.DocName == "C")
            {
                ReportMoneyReq1();
            }
            else if (this.DocName == "R")
            {
                PrintReturnForm();
            }
            else if (this.DocName == "CB")
            {
                ReportContractBorrow();
            }
        }

        #endregion

        #region Public Methods

        public void ReportMoneyReqContracts()
        {
            DataTable dtbMain = req.Report_Contract(int.Parse(this.RefNo));
            DataTable dtbSub = req.Report_ContractSub(int.Parse(this.RefNo));
            FIM_MoneyRequests.FIM_MoneyRequests mr = new FIM_MoneyRequests.FIM_MoneyRequests();
            FIM_MoneyRequests.M_FIM_MoneyRequests info = mr.GetInfo(this.RefNo);

            Dictionary<string, string> fields = new Dictionary<string, string>();

            if (dtbMain.Rows.Count > 0)
            {
                DataRow dr = dtbMain.Rows[0];
                int nLastStepNo = 0;

                if (main.ConvertNullDouble(dr["amount"]) < 500000)
                {
                    nLastStepNo = 3;
                }
                else
                {
                    nLastStepNo = (main.ConvertNullInt(send.GetLastStepNo("FIM_MONEY_REQUESTS")) ?? 0);
                }


                // Edit by Aek 2014-07-29
                // Calculate base on to_emp_seq field in table message_send, not login session 
                DataTable dtbApprover1 = send.GetCurrentApprover(dr["emp_seq"].ToString(), null, "FIM_MONEY_REQUESTS", 1);
                DataTable dtbApprover2 = send.GetCurrentApprover(dr["emp_seq"].ToString(), null, "FIM_MONEY_REQUESTS", nLastStepNo);

                fields.Add("DebtorJobsiteName", dr["debtor_job_site_name1"].ToString());
                fields.Add("BorrowNo", dr["borrow_no"].ToString());
                //ToLongDateString แสดงผลเป็น 27 กุมภาพันธ์ 2557
                //ToShortDateString แสดงผลเป็น 27/2/2557
                fields.Add("MoneyReqDate", main.ConvertNullDateTime(dr["money_req_date"]) != null
                                         ? main.ConvertNullDateTime(dr["money_req_date"]).Value.ToLongDateString() : "");
                fields.Add("BorrowStartDate", main.ConvertNullDateTime(dr["borrow_start_date"]) != null
                                            ? main.ConvertNullDateTime(dr["borrow_start_date"]).Value.ToShortDateString() : "");
                fields.Add("BorrowEndDate", main.ConvertNullDateTime(dr["borrow_end_date"]) != null
                                         ? main.ConvertNullDateTime(dr["borrow_end_date"]).Value.ToShortDateString() : "");
                fields.Add("AmountMoney", main.ConvertNullDouble(dr["amount"]) != null
                                        ? main.ConvertNullDouble(dr["amount"]).Value.ToString("#,##0.00") : "0.00");
                fields.Add("RefNo", dr["ref_no"].ToString());
                fields.Add("BorrowReturnDate", main.ConvertNullDateTime(dr["borrow_return_date"]) != null
                                             ? main.ConvertNullDateTime(dr["borrow_return_date"]).Value.ToShortDateString() : "");
                fields.Add("DebtorName", dr["debtor_name1"].ToString());
                fields.Add("DebtorPosName", dr["debtor_pos_name1"].ToString());
                //Modified by Raksakaew on Feb 24,2014
                //fields.Add("PositionName", dr["debtor_pos_name"].ToString());
                fields.Add("Province", dr["debtor_prov_name1"].ToString());
                fields.Add("MoneyReqName", dr["money_req_name"].ToString());
                fields.Add("ReturnDay", dr["return_day"].ToString());
                fields.Add("CalDateTypeName", dr["cal_date_type_name"].ToString());
                //fields.Add("AllowerName", dr["allower_name"].ToString());       
                //fields.Add("AllowerName", (main.ConvertNullDouble(dr["amount"]) != null && main.ConvertNullDouble(dr["amount"]) < 500000) ? allower2 : allower1);
                //fields.Add("AllowerPosition", (main.ConvertNullDouble(dr["amount"]) != null && main.ConvertNullDouble(dr["amount"]) < 500000) ? allowerPosition2 : allowerPosition1);
                //fields.Add("AllowerDesc", (main.ConvertNullDouble(dr["amount"]) != null && main.ConvertNullDouble(dr["amount"]) < 500000) ? allowerDesc2 : "");
                fields.Add("MoneyTextThai", mailMerge.ThaiBaht(dr["amount"].ToString()));
                //fields.Add("ApproverName", dr["approver_name"].ToString());
                //Adding on 28/4/57
                fields.Add("BgmProjName", (dr["bgm_proj_name"].ToString() != ""?"โดยเบิกจาก " + dr["bgm_proj_name"].ToString():""));

                if (dtbApprover1.Rows.Count > 0)
                {
                    DataTable dtb1 = emplist.GetInfo(main.ConvertNullInt(dtbApprover1.Rows[0]["emp_seq"]) ?? 0);
                    if (dtb1.Rows.Count > 0)
                    {
                        fields.Add("ApproverName", dtb1.Rows[0]["full_name"].ToString());
                        fields.Add("ApproverPosName", dtb1.Rows[0]["pos_name"].ToString());
                    }
                }

                if (dtbApprover2.Rows.Count > 0)
                {
                    DataTable dtb1 = emplist.GetInfo(main.ConvertNullInt(dtbApprover2.Rows[0]["emp_seq"]) ?? 0);
                    if (dtb1.Rows.Count > 0)
                    {
                        fields.Add("AllowerName", dtb1.Rows[0]["full_name"].ToString());
                        fields.Add("AllowerPosition", dtb1.Rows[0]["pos_name"].ToString());

                        fields.Add("AllowerDesc", dtb1.Rows[0]["pos_name"].ToString()=="รองผู้อำนวยการ"?"ปฏิบัติงานแทนผู้อำนวยการ":"");
                    }
                }

                //Adding on 12/4/57 for header to show record's status name.
                string strFinRecStatName;

                switch (info.record_status)
                {
                    case "W":
                        strFinRecStatName = "ดำเนินการอยู่";
                        break;

                    case "P":
                        strFinRecStatName = "รอการอนุมัติโดย " + send.GetLatestMessageStatus(this.RefNo, "fim_money_requests").to_user_name;
                        break;

                    case "A":
                        strFinRecStatName = "อนุมัติโดย " + send.GetLatestMessageStatus(this.RefNo, "fim_money_requests").to_user_name;
                        break;

                    case "R":
                        strFinRecStatName = "ตีกลับโดย " + send.GetLatestMessageStatus(this.RefNo, "fim_money_requests").to_user_name;
                        break;

                    default:
                        strFinRecStatName = "รอการยืนยันโดย " + send.GetLatestMessageStatus(this.RefNo, "fim_money_requests").to_user_name;
                        break;
                }

                fields.Add("FinRecordStatusName",strFinRecStatName);
            }

            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
            Table.Add("table1", dtbSub);

            string strTemplatePath = Server.MapPath("~/App_UI/Reports/Templates/แบบฟอร์ม_ยืมเงิน.docx");
            string strSaveAsFileName = string.Format("BR_Form_{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmss"));
            string strSaveAsPath = Server.MapPath("~/App_UI/Reports/Temp/");

            mailMerge.CreateBRTable(strTemplatePath, Table["table1"].Rows.Count, strSaveAsPath + strSaveAsFileName);
            if (mailMerge.MergeTemplate(strSaveAsPath + strSaveAsFileName, strSaveAsPath + strSaveAsFileName, fields, Table, null, null))
            {                
                mailMerge.SaveFileToClient(Response, strSaveAsPath, strSaveAsFileName, true);                
            }
        }

        public void ReportMoneyReq1()
        {
            DataTable dtbMain = req.ReportMain(int.Parse(this.RefNo));
            DataTable dtbSub = req.ReportSub(int.Parse(this.RefNo));
            FIM_MoneyRequests.FIM_MoneyRequests mr = new FIM_MoneyRequests.FIM_MoneyRequests();
            FIM_MoneyRequests.M_FIM_MoneyRequests info = mr.GetInfo(this.RefNo);

            Dictionary<string, string> fields = new Dictionary<string, string>();

            if (dtbMain.Rows.Count > 0)
            {
                DataRow dr = dtbMain.Rows[0];
                int nLastStepNo = (main.ConvertNullInt(send.GetLastStepNo("FIM_MONEY_REQUESTS", info.total_amount ?? 0)) ?? 0);

                // Edit by Aek 2014-07-29
                // Calculate base on to_emp_seq field in table message_send, not login session 
                DataTable dtbApprover1 = send.GetCurrentApprover(dr["emp_seq"].ToString(), null, "FIM_MONEY_REQUESTS", 1);
                DataTable dtbApprover2 = send.GetCurrentApprover(dr["emp_seq"].ToString(), null, "FIM_MONEY_REQUESTS", nLastStepNo);

                fields.Add("RefNo", dr["rq_ref_no"].ToString());
                fields.Add("JobSiteName", dr["job_site_name"].ToString());
                fields.Add("MoneyReqName", dr["money_req_name"].ToString());
                //Modified on 27/03/57 by Raksakaew
                fields.Add("MoneyReqDate", main.ConvertNullDateTime(dr["money_req_date"]) != null
                    ? main.ConvertNullDateTime(dr["money_req_date"]).Value.ToLongDateString() : "");
                // Comment out for new request on 10/4/57
                //fields.Add("MoneyReqDate", main.ConvertNullDateTime(dr["print_date"]) != null
                //    ? main.ConvertNullDateTime(dr["print_date"]).Value.ToLongDateString() : "");
               

                fields.Add("BorrowStartDate", main.ConvertNullDateTime(dr["borrow_start_date"]) != null
                    ? main.ConvertNullDateTime(dr["borrow_start_date"]).Value.ToLongDateString() : "");
                fields.Add("StartDateText", main.ConvertNullDateTime(dr["borrow_start_date"]) != null
                    ? "วันเริ่มกิจกรรม " : "");

                fields.Add("BorrowEndDate", main.ConvertNullDateTime(dr["borrow_end_date"]) != null
                    ? main.ConvertNullDateTime(dr["borrow_end_date"]).Value.ToLongDateString() : "");
                fields.Add("EndDateText", main.ConvertNullDateTime(dr["borrow_end_date"]) != null
                    ? "วันสิ้นสุดกิจกรรม " : "");

                fields.Add("EmpName", dr["emp_name"].ToString());
                fields.Add("PayeeName", dr["payee_name"].ToString());
                fields.Add("ProjectName", dr["bgm_proj_name"].ToString());
                //Adding on 27/3/57 by Raksakaew
                fields.Add("RQRefNo", dr["rq_ref_no"].ToString());

                fields.Add("SumAmount", (info.total_amount ?? 0).ToString("#,###.00"));
                fields.Add("SumAmountText", mailMerge.ThaiBaht((info.total_amount ?? 0).ToString("#,###.00")));
                fields.Add("EmpPosName", dr["pos_name"].ToString());

                if (dtbApprover1.Rows.Count > 0)
                {
                    DataTable dtb1 = emplist.GetInfo(main.ConvertNullInt(dtbApprover1.Rows[0]["emp_seq"]) ?? 0);
                    if (dtb1.Rows.Count > 0)
                    {
                        fields.Add("ApproverName", dtb1.Rows[0]["full_name"].ToString());
                        fields.Add("ApproverPosName", dtb1.Rows[0]["pos_name"].ToString());
                    }
                }

                if (dtbApprover2.Rows.Count > 0)
                {
                    DataTable dtb1 = emplist.GetInfo(main.ConvertNullInt(dtbApprover2.Rows[0]["emp_seq"]) ?? 0);
                    if (dtb1.Rows.Count > 0)
                    {
                        fields.Add("ApproverName2", dtb1.Rows[0]["full_name"].ToString());

                        if (dtb1.Rows[0]["pos_name"].ToString() == "รองผู้อำนวยการ")
                        {
                            fields.Add("ApproverPosName2", dtb1.Rows[0]["pos_name"].ToString()+"\n"+"ปฏิบัติงานแทนผู้อำนวยการ");
                        }
                        else
                        {
                            fields.Add("ApproverPosName2", dtb1.Rows[0]["pos_name"].ToString());
                        }
                    }
                }

                //Adding on 12/4/57 for header to show record's status name.
                string strFinRecStatName;

                switch (info.record_status)
                {
                    case "W":
                        strFinRecStatName = "ดำเนินการอยู่";
                        break;

                    case "P":
                        strFinRecStatName = "รอการอนุมัติโดย " + send.GetLatestMessageStatus(this.RefNo, "fim_money_requests").to_user_name;
                        break;

                    case "A":
                        strFinRecStatName = "อนุมัติโดย " + send.GetLatestMessageStatus(this.RefNo, "fim_money_requests").to_user_name;
                        break;

                    case "R":
                        strFinRecStatName = "ตีกลับโดย " + send.GetLatestMessageStatus(this.RefNo, "fim_money_requests").to_user_name;
                        break;

                    default:
                        strFinRecStatName = "รอการยืนยันโดย " + send.GetLatestMessageStatus(this.RefNo, "fim_money_requests").to_user_name;
                        break;
                }

                fields.Add("FinRecordStatusName", strFinRecStatName);
            }

            Dictionary<string, DataTable> dd = new Dictionary<string, DataTable>();
            dd.Add("table1", dtbSub);

            string strTemplatePath = Server.MapPath("~/App_UI/Reports/Templates/แบบฟอร์ม_เบิกเงิน.docx");
            string strSaveAsFileName = string.Format("RQ_Form_{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmss"));
            string strSaveAsPath = Server.MapPath("~/App_UI/Reports/Temp/");

            using (DocX document = DocX.Load(strTemplatePath))
            {
                var table = document.Tables[0];
                //วนลูปรายการในตาราง
                for (int i = 0; i < dtbSub.Rows.Count; i++)
                {
                    Row rx = table.InsertRow(1+i);//table.RowCount);

                    rx.Cells[0].Paragraphs[0].Append("«" + "BgmExpName" + (i + 1).ToString() + "»");
                    rx.Cells[0].Paragraphs[0].Alignment = Alignment.left;
                    rx.Cells[0].Paragraphs[0].FontSize(14);
                    rx.Cells[0].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    rx.Cells[1].Paragraphs[0].Append("«" + "Remarks" + (i + 1).ToString() + "»");
                    rx.Cells[1].Paragraphs[0].Alignment = Alignment.left;
                    rx.Cells[1].Paragraphs[0].FontSize(14);
                    rx.Cells[1].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    rx.Cells[2].Paragraphs[0].Append("«" + "Amount" + (i + 1).ToString() + "»");
                    rx.Cells[2].Paragraphs[0].Alignment = Alignment.right;
                    rx.Cells[2].Paragraphs[0].FontSize(14);
                    rx.Cells[2].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                    rx.Cells[3].Paragraphs[0].Append("«" + "AmountVat" + (i + 1).ToString() + "»");
                    rx.Cells[3].Paragraphs[0].Alignment = Alignment.right;
                    rx.Cells[3].Paragraphs[0].FontSize(14);
                    rx.Cells[3].Paragraphs[0].Font(new FontFamily("TH SarabunPSK"));
                }

                document.SaveAs(strSaveAsPath + strSaveAsFileName);
            }

            if (mailMerge.MergeTemplate(strSaveAsPath + strSaveAsFileName, strSaveAsPath + strSaveAsFileName, fields, dd, null, null))
            {
                mailMerge.SaveFileToClient(Response, strSaveAsPath, strSaveAsFileName, true);               
            }
        }

        public void PrintReturnForm()
        {
            DataTable dtbMain = dtbMain = re2.getMoneyReturnReport(this.RefNo, this.RefReturn);
            DataTable dtbSub = ConvertToDataTable(red.GetMoneyReqDtls(this.RefReturn, this.RefNo));

            FIM_MoneyRequests.FIM_MoneyRequests mr = new FIM_MoneyRequests.FIM_MoneyRequests();
            FIM_MoneyRequests.M_FIM_MoneyRequests info = mr.GetInfo(this.RefNo);

            FIM_MoneyReturns.FIM_MoneyReturns rtn = new FIM_MoneyReturns.FIM_MoneyReturns();
            FIM_MoneyReturns.M_FIM_MoneyReturns info2 = rtn.GetInfo(this.RefReturn);

            Dictionary<string, string> fields = new Dictionary<string, string>();

            if (dtbMain.Rows.Count > 0)
            {
                DataRow dr = dtbMain.Rows[0];

                int nLastStepNo = 0;

                if (info.total_amount < 500000)
                {
                    nLastStepNo = 3;
                }
                else
                {
                    nLastStepNo = (main.ConvertNullInt(send.GetLastStepNo("FIM_MONEY_REQUESTS")) ?? 0);
                }

                // Edit by Aek 2014-07-29
                // Calculate base on to_emp_seq field in table message_send, not login session 
                DataTable dtbApprover1 = send.GetCurrentApprover(dr["emp_seq"].ToString(), null, "FIM_MONEY_REQUESTS", 1);
                DataTable dtbApprover2 = send.GetCurrentApprover(dr["emp_seq"].ToString(), null, "FIM_MONEY_REQUESTS", nLastStepNo);

                fields.Add("DebtorJobsiteName", dr["debtor_job_site_name"].ToString());
                fields.Add("BorrowNo", dr["borrow_no"].ToString());
                fields.Add("ReturnDate", main.ConvertNullDateTime(dr["return_date"]) != null
                                         ? main.ConvertNullDateTime(dr["return_date"]).Value.ToLongDateString() : "");
                fields.Add("MoneyReqDate", main.ConvertNullDateTime(dr["money_req_date"]) != null
                                         ? main.ConvertNullDateTime(dr["money_req_date"]).Value.ToLongDateString() : "");
                fields.Add("BorrowStartDate", main.ConvertNullDateTime(dr["borrow_start_date"]) != null
                                            ? main.ConvertNullDateTime(dr["borrow_start_date"]).Value.ToShortDateString() : "");
                fields.Add("BorrowEndDate", main.ConvertNullDateTime(dr["borrow_end_date"]) != null
                                         ? main.ConvertNullDateTime(dr["borrow_end_date"]).Value.ToShortDateString() : "");

                //fields.Add("SumAmountRtn", (info.return_amount ?? 0).ToString("#,###.00"));

                fields.Add("SumAmount", main.ConvertNullDouble(dr["sum_amount"]) != null
                                        ? main.ConvertNullDouble(dr["sum_amount"]).Value.ToString("#,##0.00") : "0.00");
                fields.Add("RefNo", dr["ref_no"].ToString());

                //fields.Add("BorrowReturnDate", main.ConvertNullDateTime(dr["borrow_return_date"]) != null
                //                             ? main.ConvertNullDateTime(dr["borrow_return_date"]).Value.ToShortDateString() : "");

                fields.Add("DebtorName", dr["debtor_name"].ToString());
                fields.Add("MoneyReqName", dr["money_req_name"].ToString());
                fields.Add("RefNoRQ", dr["ref_no_rq"].ToString());

                //fields.Add("BgmProjOperCode", dr["bgm_proj_oper_code"].ToString());
                //fields.Add("BgmProjOperName", dr["bgm_proj_oper_name"].ToString());
                //fields.Add("MoneyTextThai", mailMerge.ThaiBaht(dr["sum_amount"].ToString()));
                //fields.Add("MoneyTextThai", mailMerge.ThaiBaht((info.return_amount ?? 0).ToString("#,###.00")));

                fields.Add("EmpName", dr["emp_name"].ToString());
                fields.Add("JobSiteName", dr["debtor_job_site_name"].ToString());

                //Modified on 16/5/57
                //fields.Add("AccrAmount", ((info.total_amount ?? 0) - (info.return_amount ?? 0) - (info.receive_amount ?? 0)).ToString("#,###.00"));
                //if ((info.total_amount ?? 0) != (info.return_amount ?? 0))
                if (info2 != null)
                {
                    if ((info2.total_bath_amount_accum.Value).ToString("#,##0.00") != "0.00")
                    {
                        fields.Add("SumAmountRtn", (info.return_amount ?? 0).ToString("#,###.00"));
                        fields.Add("MoneyTextThai", mailMerge.ThaiBaht((info.return_amount ?? 0).ToString("#,###.00")));
                        fields.Add("AccrAmount", (((info.total_amount ?? 0) - (info.return_amount ?? 0) - (info.receive_amount ?? 0)) == 0 ? "" : ((info.total_amount ?? 0) - (info.return_amount ?? 0) - (info.receive_amount ?? 0)).ToString("#,###.00")));
                    }
                    else
                    {
                        fields.Add("SumAmountRtn", "");
                        fields.Add("MoneyTextThai", "");
                        fields.Add("AccrAmount", (info.return_amount ?? 0).ToString("#,###.00"));
                    }
                }
                
                fields.Add("SumInvAccr", (info.total_amount ?? 0).ToString("#,###.00"));
                fields.Add("SumInvAccrText", mailMerge.ThaiBaht((info.total_amount ?? 0).ToString("#,###.00")));

                //Adding on 17/4/57
                fields.Add("EmpPosName",dr["pos_name"].ToString());

                //Adding on 29/4/57
                fields.Add("BgmProjName",(dr["bgm_proj_name"].ToString() != ""?dr["bgm_proj_name"].ToString():""));

                //Adding on 6/5/57
                fields.Add("SumAmountText", mailMerge.ThaiBaht(main.ConvertNullDouble(dr["sum_amount"]) != null
                                        ? main.ConvertNullDouble(dr["sum_amount"]).Value.ToString("#,##0.00") : "0.00"));

                //Adding on 4/6/57
                fields.Add("Remarks", (dr["remarks"].ToString() != "" ? dr["remarks"].ToString() : ""));

                if (dtbApprover1.Rows.Count > 0)
                {
                    DataTable dtb1 = emplist.GetInfo(main.ConvertNullInt(dtbApprover1.Rows[0]["emp_seq"]) ?? 0);
                    if (dtb1.Rows.Count > 0)
                    {
                        fields.Add("ApproverName", dtb1.Rows[0]["full_name"].ToString());
                        fields.Add("ApproverPosName", dtb1.Rows[0]["pos_name"].ToString());
                    }
                }

                if (dtbApprover2.Rows.Count > 0)
                {
                    DataTable dtb1 = emplist.GetInfo(main.ConvertNullInt(dtbApprover2.Rows[0]["emp_seq"]) ?? 0);
                    if (dtb1.Rows.Count > 0)
                    {
                        fields.Add("ApproverName2", dtb1.Rows[0]["full_name"].ToString());
                        if (dtb1.Rows[0]["pos_name"].ToString() == "รองผู้อำนวยการ")
                        {
                            fields.Add("ApproverPosName2", dtb1.Rows[0]["pos_name"].ToString() + "\n" + "ปฏิบัติงานแทนผู้อำนวยการ");
                        }
                        else
                        {
                            fields.Add("ApproverPosName2", dtb1.Rows[0]["pos_name"].ToString());
                        }
                    }
                }
            }

            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
            Table.Add("table1", dtbSub);

            bool status = false;         

            string strTemplatePath = Server.MapPath("~/App_UI/Reports/Templates/แบบฟอร์ม_คืนเงิน.docx");
            string strSaveAsFileName = string.Format("CLS_Form_{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmss"));
            string strSaveAsPath = Server.MapPath("~/App_UI/Reports/Temp/");

            //Modified on 5/6/2557 
            //if (((info.total_amount ?? 0) == (info.return_amount ?? 0)) || (info.return_amount ?? 0)==0)

            mailMerge.CreateCLSTable(strTemplatePath, dtbSub.Rows.Count, strSaveAsPath + strSaveAsFileName);

            if ((info2 == null)||((info2.total_bath_amount_accum.Value).ToString("#,##0.00") == "0.00"))
            {
                status = mailMerge.MergeTemplate(strSaveAsPath + strSaveAsFileName, strSaveAsPath + strSaveAsFileName, fields, null, null, null);
            }
            else
            {
                status = mailMerge.MergeTemplate(strSaveAsPath + strSaveAsFileName, strSaveAsPath + strSaveAsFileName, fields, Table, null, null);
            }

            if (status)
            {
                mailMerge.SaveFileToClient(Response, strSaveAsPath, strSaveAsFileName, false);
            }
        }

        public DataTable ConvertToDataTable<T>(IList<T> data)
        {
            System.ComponentModel.PropertyDescriptorCollection properties =
                 System.ComponentModel.TypeDescriptor.GetProperties(typeof(T));
            DataTable table = new DataTable();
            foreach (System.ComponentModel.PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
            foreach (T item in data)
            {
                DataRow row = table.NewRow();
                foreach (System.ComponentModel.PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }
            return table;

        }

        public void ReportContractBorrow()
        {
            DataTable dtbMain = req.Report_Contract(int.Parse(this.RefNo));
            DataTable dtbSub = req.Report_ContractSub(int.Parse(this.RefNo));

            Dictionary<string, string> fields = new Dictionary<string, string>();

            if (dtbMain.Rows.Count > 0)
            {
                DataRow dr = dtbMain.Rows[0];

                int nLastStepNo = 0;

                if (main.ConvertNullDouble(dr["amount"]) < 500000)
                {
                    nLastStepNo = 3;
                }
                else
                {
                    nLastStepNo = (main.ConvertNullInt(send.GetLastStepNo("FIM_MONEY_REQUESTS")) ?? 0);
                }

                // Edit by Aek 2014-07-29
                // Calculate base on to_emp_seq field in table message_send, not login session 
                DataTable dtbApprover1 = send.GetCurrentApprover(dr["emp_seq"].ToString(), null, "FIM_MONEY_REQUESTS", 1);
                DataTable dtbApprover2 = send.GetCurrentApprover(dr["emp_seq"].ToString(), null, "FIM_MONEY_REQUESTS", nLastStepNo);

                fields.Add("SysJobsiteName", main.GetSystemJobsiteName());
                fields.Add("BorrowNo", dr["borrow_no"].ToString());
                fields.Add("RefNo", dr["ref_no"].ToString());
                fields.Add("BorrowReturnDate", main.ConvertNullDateTime(dr["borrow_return_date"]) != null
                    ? main.ConvertNullDateTime(dr["borrow_return_date"]).Value.ToShortDateString() : "");
                fields.Add("DebtorName", dr["debtor_name1"].ToString().Trim() != "" ? dr["debtor_name1"].ToString() : dr["debtor_name2"].ToString());
                fields.Add("PositionName", dr["debtor_pos_name1"].ToString().Trim() != "" ? dr["debtor_pos_name1"].ToString() : dr["debtor_pos_name2"].ToString());
                fields.Add("Province", dr["debtor_prov_name1"].ToString());
                fields.Add("DebtorJobsiteName", dr["debtor_job_site_name1"].ToString().Trim() != "" ? dr["debtor_job_site_name1"].ToString() : dr["debtor_job_site_name2"].ToString());
                fields.Add("MoneyReqName", dr["money_req_name"].ToString());
                fields.Add("ReturnDay", dr["return_day"].ToString());
                fields.Add("CalDateTypeName", dr["cal_date_type_name"].ToString());
                //fields.Add("AllowerName", dr["allower_name"].ToString());
                fields.Add("Amount", main.ConvertNullDouble(dr["amount"]) != null
                    ? main.ConvertNullDouble(dr["amount"]).Value.ToString("#,##0.00") : "0.00");
                fields.Add("MoneyTextThai", mailMerge.ThaiBaht(dr["amount"].ToString()));
                //Adding on May 2,2014
                fields.Add("MoneyReqDate", main.ConvertNullDateTime(dr["money_req_date"]) != null
                                         ? main.ConvertNullDateTime(dr["money_req_date"]).Value.ToLongDateString() : "");

                if (dtbApprover2.Rows.Count > 0)
                {
                    DataTable dtb1 = emplist.GetInfo(main.ConvertNullInt(dtbApprover2.Rows[0]["emp_seq"]) ?? 0);
                    if (dtb1.Rows.Count > 0)
                    {
                        fields.Add("AllowerName", dtb1.Rows[0]["full_name"].ToString());
                        
                        if (dtb1.Rows[0]["pos_name"].ToString() == "รองผู้อำนวยการ")
                        {
                            fields.Add("AllowerPosition", dtb1.Rows[0]["pos_name"].ToString() + "\n" + "ปฏิบัติงานแทนผู้อำนวยการ");
                        }
                        else
                        {
                            fields.Add("AllowerPosition", dtb1.Rows[0]["pos_name"].ToString());
                        }
                    }
                }
            }

            Dictionary<string, DataTable> Table = new Dictionary<string, DataTable>();
            Table.Add("table1", dtbSub);

            string strTemplatePath = Server.MapPath("~/App_UI/Reports/Templates/สัญญาการยืมเงิน.docx");
            string strSaveAsFileName = string.Format("BRContract{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
            string strSaveAsPath = Server.MapPath("~/App_UI/Reports/Temp/");

            if (mailMerge.MergeTemplate(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, Table, null, null))
            {
                mailMerge.SaveFileToClient(Response, strSaveAsPath, strSaveAsFileName, true);
            }
        }

        #endregion

    }
}